package com.zryc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zryc.service.IMenuService;
import com.zryc.service.IUserService;
import com.zryc.shop.entity.User;
import com.zryc.shop.utils.JwtUtils;
import com.zryc.shop.utils.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xujiajun
 * @since 2022-10-29
 */
@RestController
@RequestMapping(path = "/admin")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private IUserService userService;
    @RequestMapping(path = "/login",consumes = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.POST)
    @ApiOperation("登录认证")
    public Result<Object> login(@RequestBody User user){
        User loginUser=userService.login(user.getUsername(),user.getPassword());
        if (loginUser!=null){
            //登录成功会生成一个令牌,将令牌时间改为3小时
            String jwt= JwtUtils.generageJwt(loginUser.getUid().toString(),loginUser.getUsername(),3*60*60*1000L);
            Map<String,Object> tokenInfo= new HashMap<>();
            tokenInfo.put("tokenHead","Bearer ");
            tokenInfo.put("token",jwt);
            //更新一下账号的最新登陆时间
            UpdateWrapper<User> wrapper=new UpdateWrapper<>();
            wrapper.eq("username",loginUser.getUsername());
            wrapper.set("login_time", LocalDateTime.now());
            userService.update(wrapper);
            return new Result<Object>(true,200,"登陆成功",tokenInfo);
        }
        return new Result<>(false,4011,"登陆失败:用户名或密码错误!");
    }

    @Autowired
    private IMenuService menuService;

    @RequestMapping(path = "/info",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation("获取用户详细信息")
    public Result<User> info(@RequestHeader("Authorization") String token) throws Exception {
        Claims claims=JwtUtils.parseJwt(token.split(" ")[1]);//解析token
        String uid=claims.get("userId",String.class);//从token中获取用户ID
        User userinfo=userService.getById(uid);//使用userid查询用户信息
        if (userinfo!=null){
            userinfo.setMenus(menuService.list());//获取到列表并封装到用户对象
            userinfo.getRoles().add("超级管理员");
            return new Result<>(true,200,"查询成功",userinfo);
        }
        return new Result<>(false,400,"查询失败，用户ID不存在");
    }

    @GetMapping("/list")
    @ApiOperation("查询用户(管理员)列表")
    public Result<IPage> list(@RequestParam(required = false) @ApiParam("查询关键字，用户名/姓名") String keyword,
                              @RequestParam(defaultValue = "1") @ApiParam("查询页号") Integer pageNum,
                              @RequestParam(defaultValue = "5") @ApiParam("每页几条") Integer pageSize){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)){
            wrapper.like("username",keyword);
            wrapper.or();
            wrapper.like("nick_name",keyword);
        }
        IPage page= userService.page(new Page<>(pageNum,pageSize),wrapper);
        return new Result<>(true,200,"用户列表查询完成",page);
    }

    @PostMapping(path = "/register",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("添加管理员")
    public Result register(@RequestBody User user){
        try {
            user.setPassword(BCrypt.hashpw(user.getPassword(),BCrypt.gensalt()));
            userService.save(user);
            return new Result(true,200,"添加成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,500,"添加失败");
        }
    }

    @PostMapping(value = "/update/{pid}",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("修改管理员信息")
    public Result update(@ApiParam(required = true) @PathVariable Integer pid,@RequestBody User user){
        try{
            user.setUid(pid);
            userService.updateById(user);
            return new Result(true,200,"修改成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,500,"修改失败");
        }
    }

    @PostMapping(value = "/updateStatus/{uid}")
    @ApiOperation("修改管理员状态")
    public Result updateStatus(@ApiParam(value = "用户ID",required = true) @PathVariable Integer uid,
                               @ApiParam(value = "用户状态",required = true) @RequestParam Integer status){
        UpdateWrapper wrapper=new UpdateWrapper();
        wrapper.eq("uid",uid);
        wrapper.set("status", status);
        if (userService.update(wrapper)){
            return new Result(true,200,"用户状态修改成功");
        }else{
            return new Result(false,304,"用户状态修改失败,用户ID可能不存在");
        }
    }

    @PostMapping(path = "/delete/{uid}")
    @ApiOperation("删除管理员")
    public Result delete(@ApiParam(value = "用户ID",required = true) @PathVariable Integer uid){
        if (userService.removeById(uid)){
            return new Result(true,200,"删除成功");
        }else{
            return new Result(false,304,"删除失败");
        }

    }
    @PostMapping("/logout")
    @ApiOperation("管理员登出")
    public Result logout(HttpSession session){
        if (session!=null){
            session.invalidate();
        }
        return new Result(true,200,"logout success");

    }
    
    
    
    
    
    
    
    
    
    
    
    
}
